var http = {};

http.quest = function (option, callback) {
    var url = option.url;
    var method = option.method;
    var data = option.data;
    var timeout = option.timeout || 0;

    var xhr = new XMLHttpRequest();
    (timeout > 0) && (xhr.timeout = timeout);
    xhr.onload  = function () {
        if (xhr.readyState == 4) {
            var result = xhr.responseText;
            try {result = JSON.parse(xhr.responseText);} catch (e) {}
            callback && callback(null, result);
        }
    }.bind(this);

    if(method == "get"){
        if(data != undefined){
            for (var kk in data) {
                url += "&"+kk+"="+data[kk]
            }
            data = {};
        }
    }

    xhr.open(method, url, true);

    if(method == "post"){
        //Content-Type: application/json
        xhr.setRequestHeader('Content-Type','application/json');
    }

    if(typeof data === 'object'){
        try{
            data = JSON.stringify(data);
        }catch(e){}
    }
    var booleen = true;
    for (var httpkey in httpUrl) {
        if(url.indexOf(httpUrl[httpkey])>-1){
            booleen = false;
        }
    }
    if(booleen){
        var token = $.session.get("access_token");
        if(new Date().getTime() > $.session.get("exp")){
            window.location.href = "login.html";
        }
        if (token != null) {
            // 将云识别认证token写在请求头中
            xhr.setRequestHeader('Authorization', "Bearer "+token);
        }
    }
    xhr.send(data);
    xhr.ontimeout = function () {
        callback && callback('timeout');
        console.log('%c连%c接%c超%c时', 'color:red', 'color:orange', 'color:purple', 'color:green');
    };
};

http.get = function (url, callback) {
    var option = url.url ? url : { url: url };
    option.method = 'get';
    this.quest(option, callback);
};

http.post = function (option, callback) {
    option.method = 'post';
    this.quest(option, callback);
};